package com.topofstack.flp.utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.regex.Pattern;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Rect;
import android.net.Uri;
import android.os.Environment;
import android.provider.BaseColumns;
import android.provider.MediaStore;
import android.util.Log;

public class Utils {
	public static void showAlertMessage(Context context, String title,
			String message) {
		final AlertDialog.Builder builder = new AlertDialog.Builder(context);
		builder.setMessage(message).setCancelable(false)
				.setPositiveButton("OK", new DialogInterface.OnClickListener() {
					public void onClick(final DialogInterface dialog,
							final int id) {

					}
				});
		final AlertDialog alert = builder.create();
		alert.setTitle(title);
		alert.show();
	}

	public static final Pattern EMAIL_ADDRESS_PATTERN = Pattern
			.compile("[a-zA-Z0-9\\+\\.\\_\\%\\-\\+]{1,256}" + "\\@"
					+ "[a-zA-Z0-9][a-zA-Z0-9\\-]{0,64}" + "(" + "\\."
					+ "[a-zA-Z0-9][a-zA-Z0-9\\-]{0,25}" + ")+");
	public static final Pattern URL_PATTERN = Pattern
			.compile("\\b(https?|ftp|file)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]");

	public static boolean checkEmail(String email) {
		return EMAIL_ADDRESS_PATTERN.matcher(email).matches();
	}

	public static boolean checkURL(String url) {

		return URL_PATTERN.matcher(url).matches();
	}

	public static String getAssetsAsString(Context context, String fileName)
			throws Exception {
		InputStream is = context.getAssets().open(fileName);
		BufferedReader reader = new BufferedReader(new InputStreamReader(is));
		StringBuilder sb = new StringBuilder();
		String line = null;
		while ((line = reader.readLine()) != null) {
			sb.append(line + "\n");
		}
		is.close();
		return sb.toString();
	}

	public static String getRealPathFromURI(Uri contentUri, Activity activity)
			throws Exception {
		// can post image
		String[] proj = { MediaStore.Images.Media.DATA };
		Cursor cursor = activity.managedQuery(contentUri, proj, // Which columns
																// to return
				null, // WHERE clause; which rows to return (all rows)
				null, // WHERE clause selection arguments (none)
				null); // Order-by clause (ascending by name)
		int column_index = cursor
				.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
		cursor.moveToFirst();

		return cursor.getString(column_index);
	}

	public static String[] getRealPathFromURIAndID(Uri contentUri,
			Activity activity) throws Exception {
		// can post image
		String[] ret = new String[2];
		try {
			String[] proj = { MediaStore.Images.Media.DATA,
					android.provider.BaseColumns._ID };
			Cursor cursor = activity.managedQuery(contentUri, proj, // Which
																	// columns
																	// to return
					null, // WHERE clause; which rows to return (all rows)
					null, // WHERE clause selection arguments (none)
					null); // Order-by clause (ascending by name)
			int column_index_data = cursor
					.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
			int column_index_id = cursor
					.getColumnIndexOrThrow(android.provider.BaseColumns._ID);
			cursor.moveToFirst();

			ret[0] = cursor.getString(column_index_data);
			ret[1] = cursor.getString(column_index_id);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return ret;
	}
	
	public static final int getLastGalleryImageId(Activity activity) {
		final String[] imageColumns = { MediaStore.Images.Media._ID };
		final String imageOrderBy = MediaStore.Images.Media._ID + " DESC";
		Cursor imageCursor = activity.managedQuery(
				MediaStore.Images.Media.EXTERNAL_CONTENT_URI, imageColumns,
				null, null, imageOrderBy);
		if (imageCursor.moveToFirst()) {
			int id = imageCursor.getInt(imageCursor
					.getColumnIndex(MediaStore.Images.Media._ID));
			imageCursor.close();
			return id;
		} else {
			return 0;
		}
	}
	public static void removeGalleryImage(Activity activity,int id) {
		ContentResolver cr = activity.getContentResolver();
		int delete = cr.delete(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
				MediaStore.Images.Media._ID + "=?",
				new String[] { Long.toString(id) });
	}
	public static void removeImage(Activity activity,int id) {
		ContentResolver cr = activity.getContentResolver();
		int delete = cr.delete(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
				android.provider.BaseColumns._ID + "=?",
				new String[] { Long.toString(id) });
	}

	public static String[] getLastImageDataAndID(Uri contentUri,Activity context) {
		String ret[] = new String[2];
		final String[] imageColumns = { MediaStore.Images.Media.DATA,
				MediaStore.Images.Media._ID };
		final String imageOrderBy = MediaStore.Images.Media._ID + " DESC";
		Cursor imageCursor = context.managedQuery(
				MediaStore.Images.Media.EXTERNAL_CONTENT_URI,imageColumns,
				null, null, imageOrderBy);
		if (imageCursor.moveToFirst()) {
			String data = imageCursor.getString(imageCursor
					.getColumnIndex(MediaStore.Images.Media.DATA));
			int id = imageCursor.getInt(imageCursor
					.getColumnIndex(MediaStore.Images.Media._ID));
			Log.i("DREG", "ID =" + id);
			ret[0] = data;
			ret[1] = Integer.toString(id);
		}
		return ret;
	}

	public static String getRealVideoPathFromURI(Uri contentUri,
			Activity activity) throws Exception {
		// can post image
		String[] proj = { MediaStore.Video.Media.DATA };
		Cursor cursor = activity.managedQuery(contentUri, proj, // Which columns
																// to return
				null, // WHERE clause; which rows to return (all rows)
				null, // WHERE clause selection arguments (none)
				null); // Order-by clause (ascending by name)
		int column_index = cursor
				.getColumnIndexOrThrow(MediaStore.Video.Media.DATA);
		cursor.moveToFirst();

		return cursor.getString(column_index);
	}

	public static File convertImageUriToFile(Uri imageUri, Activity activity)
			throws Exception {
		String path = getRealPathFromURI(imageUri, activity);
		if (path != null) {
			return new File(path);
		} else {
			return null;
		}
	}

	public static File convertVideoUriToFile(Uri videoUri, Activity activity)
			throws Exception {
		String path = getRealVideoPathFromURI(videoUri, activity);
		if (path != null) {
			return new File(path);
		} else {
			return null;
		}
	}

	// public static File convertImageUriToFile(Uri imageUri, Activity activity)
	// {
	//
	// Cursor cursor = null;
	// try {
	// String[] proj = { MediaStore.Images.Media.DATA,
	// MediaStore.Images.Media._ID,
	// MediaStore.Images.ImageColumns.ORIENTATION };
	// cursor = activity.managedQuery(imageUri, proj, // Which columns to
	// // return
	// null, // WHERE clause; which rows to return (all rows)
	// null, // WHERE clause selection arguments (none)
	// null); // Order-by clause (ascending by name)
	// int file_ColumnIndex = cursor
	// .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
	// if (cursor.moveToFirst()) {
	// return new File(cursor.getString(file_ColumnIndex));
	// }
	// return null;
	// } finally {
	// if (cursor != null) {
	// cursor.close();
	// }
	// }
	//
	// }

	public static String getPath(Activity a, Uri uri) {
		String[] projection = { MediaStore.Images.Media.DATA };
		Cursor cursor = a.managedQuery(uri, projection, null, null, null);
		int column_index = cursor
				.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
		cursor.moveToFirst();
		return cursor.getString(column_index);
	}

	public static Bitmap decodeFile(File f, int maxWidth, int maxHeight) {
		Bitmap ret = null;
		try {
			// Decode image size
			BitmapFactory.Options o = new BitmapFactory.Options();
			o.inJustDecodeBounds = true;
			BitmapFactory.decodeStream(new FileInputStream(f), null, o);
			BitmapFactory.Options o2 = new BitmapFactory.Options();
			o2.inSampleSize = 1;
			ret = BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
			int width_tmp = o.outWidth;
			int height_tmp = o.outHeight;
			if (width_tmp > maxWidth || height_tmp > maxHeight) {

				float scale = Math.min((maxWidth * 1.0F) / width_tmp,
						(maxHeight * 1.0F) / height_tmp);
				Matrix matrix = new Matrix();
				matrix.postScale(scale, scale);
				Bitmap resizedBitmap = Bitmap.createBitmap(ret, 0, 0,
						width_tmp, height_tmp, matrix, true);
				ret.recycle();
				ret = resizedBitmap;

			}
		} catch (Exception e) {
			Log.i("DREG", e.getMessage());
			e.printStackTrace();
		}
		return ret;
	}

	public static float getDPIFactor(android.app.Activity activity) {
		android.util.DisplayMetrics metrics = new android.util.DisplayMetrics();
		activity.getWindowManager().getDefaultDisplay().getMetrics(metrics);
		return metrics.density;
	}

	public static Bitmap decodeFile(File f, int width) {
		Bitmap ret = null;
		try {
			Bitmap temp = BitmapFactory.decodeStream(new FileInputStream(f));
			ret = Bitmap.createBitmap(width, width, Bitmap.Config.ARGB_8888);
			Canvas comboImage = new Canvas(ret);

			// Rect rDest = new Rect(0, 0, width, width);
			Rect rDest = new Rect(1, 1, width - 1, width - 1);
			int min = Math.min(temp.getWidth(), temp.getHeight());
			Rect rSrc = new Rect((temp.getWidth() - min) / 2,
					(temp.getHeight() - min) / 2, (temp.getWidth() + min) / 2,
					(temp.getHeight() + min) / 2);
			comboImage.drawBitmap(temp, rSrc, rDest, null);
			Paint paint = new Paint();
			paint.setColor(0xFF525252);
			comboImage.drawLine(0, 0, width - 1, 0, paint);
			comboImage.drawLine(0, width - 1, width - 1, width - 1, paint);
			comboImage.drawLine(0, 0, 0, width - 1, paint);
			comboImage.drawLine(width - 1, 0, width - 1, width - 1, paint);
			comboImage.save();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return ret;
	}

	public static final ProgressDialog getProgressDialog(Context context,
			String title, String message) {
		ProgressDialog progressDialog = new ProgressDialog(context);
		progressDialog.setTitle(title);
		progressDialog.setMessage(message);
		progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		progressDialog.setCancelable(true);
		progressDialog.setIndeterminate(true);
		return progressDialog;
	}

	public static String downloadFile(String Url) {
		String filepath = null;
		try {
			URL url = new URL(Url);
			HttpURLConnection urlConnection = (HttpURLConnection) url
					.openConnection();

			urlConnection.setRequestMethod("GET");
			urlConnection.setDoOutput(true);

			urlConnection.connect();
			File SDCardRoot = Environment.getExternalStorageDirectory();

			String[] temp = Url.split("/");
			String filename = "" + temp[temp.length - 1]; // you can download to
															// any type of file
															// ex:.jpeg (image)
															// ,.txt(text
															// file),.mp3 (audio
															// file)
			File file = new File(SDCardRoot, filename);
			if (file.createNewFile()) {
				file.createNewFile();
			}

			FileOutputStream fileOutput = new FileOutputStream(file);

			InputStream inputStream = urlConnection.getInputStream();

			int totalSize = urlConnection.getContentLength();
			// variable to store total downloaded bytes
			int downloadedSize = 0;

			byte[] buffer = new byte[1024];
			int bufferLength = 0; // used to store a temporary size of the
									// buffer

			Log.i("DREG", "WII DOWNLOAD=" + totalSize);
			while ((bufferLength = inputStream.read(buffer)) != 1) {
				Log.i("DREG", "DOWNLOADED=" + bufferLength);
				fileOutput.write(buffer, 0, bufferLength);
				downloadedSize += bufferLength;
			}
			Log.i("DREG", "WII DOWNLOADED=" + totalSize);
			fileOutput.close();
			if (downloadedSize == totalSize) {
				filepath = file.getPath();
			}

		} catch (Exception e) {
			filepath = null;
			e.printStackTrace();
		}
		return filepath;

	}
}
